﻿package modular {
	import modular.events.ModuleEvent;	
	import modular.module.PreloaderModule;	
	
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.text.TextField;
	
	import ch.sfug.log.Logger;
	import ch.sfug.log.output.LogPanel;
	import ch.sfug.net.loader.XMLLoader;	

	/**
	 * @author mich
	 */
	public class BootLoader extends ModuleSetLoader {

		private var xml:XMLLoader;

		public function BootLoader() {
			
			super();
			
			stage.align = StageAlign.TOP_LEFT;
			stage.scaleMode = StageScaleMode.NO_SCALE;
			
			Library.register( stage.loaderInfo.applicationDomain, "root" );
			Modular.setRootLoader( this );
			
			createDefaultPreloader();
			removeEventListener( ModuleEvent.INFO_CHANGED, onInfoChanged );

			loadAppXML();
		}
		

		
		
		private function loadAppXML():void {
			xml = new XMLLoader( getApplicationXML() );
			xml.addEventListener( IOErrorEvent.IO_ERROR, onError);
			xml.addEventListener( SecurityErrorEvent.SECURITY_ERROR, onError );
			xml.addEventListener( ErrorEvent.ERROR, onError );
			xml.addEventListener( Event.COMPLETE, onXML );
			
			xml.load();
		}

		
		private function onXML( event:Event ):void {
			
			var bootxml:XML = xml.getResult();
			
			if( bootxml.@dev != undefined ) {
				var panel:LogPanel = new LogPanel( stage );
				var dev:String = bootxml.@dev;
				if( dev == "info" ) Logger.appendOutput( panel, Modular.LOG_INFO );
				Logger.appendOutput( panel, Modular.LOG_ERROR );
			}
			
			Logger.log( "boot.xml: " + bootxml, Modular.LOG_INFO );
			
			info = new ModuleInfo( bootxml );
			
			parseXML( bootxml );
		}

		
		private function onError( event:ErrorEvent ):void {
			var txt:TextField = new TextField( );
			txt.width = 600;
			txt.text = event.text;
			txt.background = true;
			txt.border = true;
			addChild(txt);
		}


		private function createDefaultPreloader():void {
			var preloaderItem:ModuleSetItem = new ModuleSetItem( <Module class="modular.module.PreloaderModule" /> );
			preloaderItem.createInstanceOn( this);
			libLoader.preloader = PreloaderModule( preloaderItem.module );
		}

		
		private function getApplicationXML():String {
			if( stage.loaderInfo.parameters[ "bootxml" ] != null ) {
				return stage.loaderInfo.parameters[ "bootxml" ];
			} else {
				return "boot.xml";
			}
		}
	}
}
